import { defineComponent, nextTick, onUnmounted, ref } from "vue";

const EwgDialog = defineComponent({
  name: "EwgDialog",
  props: {
    modal: {
      type: Boolean,
      default: false,
    },
  },
  emits: {
    close: () => true,
  },
  setup(_props, ctx) {
    const modalOpen = ref(false);
    const modalclose = () => {
      ctx.emit("close");
    };
    const handleKeydown = (e: any) => {
      const { code } = e;
      if (code === "Escape") {
        modalclose();
      }
    };
    const close = (cb?: Function) => {
      // eslint-disable-next-line no-unused-expressions
      cb && cb();
      modalOpen.value = false;
      window.removeEventListener("keydown", handleKeydown);
    };
    const open = (cb?: Function) => {
      modalOpen.value = true;
      window.addEventListener("keydown", handleKeydown);
      nextTick(() => {
        // eslint-disable-next-line no-unused-expressions
        cb && cb();
      });
    };
    onUnmounted(() => {
      window.removeEventListener("keydown", handleKeydown);
    });
    return {
      modalOpen,
      close,
      modalclose,
      open,
      handleKeydown,
    };
  },
});
export default EwgDialog;
export type EwgDialogRefs = InstanceType<typeof EwgDialog>;
